<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/3/17
 * Time: 15:22
 */

namespace App\Rep;


use App\Models\Order;
use App\Models\OrderChild;
use App\Models\OrderKucunLog;
use App\Models\OrderSecond;
use App\Models\ProductJobType;
use App\Models\SemiFinishProduct;
use Illuminate\Support\Facades\DB;

class OrderChildRep
{

    /**获取生产订单列表**/
    public function getOrderChildListRep($params){
        $list = Order::Schedule($params)
            ->with(['color'=>function($q){
                 $q->select('id','color');
            },'product'=>function($q){
                 $q->select('id','product_name')->with('job_type');
            },'customer'=>function($q){
                 $q->select('id','customer_name','customer_address');
            },'modelNumber'=>function($q){
                 $q->select('id','model_number','file_id')->with(['file']);
            },'specification'=>function($q){
                 $q->select('id','specification');
            },'accountExecutive'=>function($q){
                 $q->select('id','company_name');
            },'order_second'=>function($q){
                 $q->with(['order_child'=>function($q){
                    $q->orderBy('sort','asc')->with(['job_type','employee']);
                },'models'=>function($q){
                    $q->select('modelid','modelname','pid');
                },'product'=>function($q){
                    $q->select('id','product_name');
                },'model_number'=>function($q){
                    $q->select('id','model_number');
                },'specification'=>function($q){
                    $q->select('id','specification');
                },'color'=>function($q){
                    $q->select('id','color');
                }]);
            }])
            ->orderBy('id','desc')
            ->paginate($params['per_page']??10);
        foreach($list as $k=>$v){
            foreach($v->order_second as $kk=>$vv){
                $job_type_list = ProductJobType::where('product_id',$vv['product_id'])
                    ->with(['job_type'=>function($q){
                        $q->select('id','job_type');
                    }])
                    ->orderBy('sort','asc')
                    ->get()
                    ->toArray();
                foreach($job_type_list as $key=>$val){
                    //未领取
                    $wlq_count = OrderChild::where('order_id',$vv->order_id)
                        ->where('order_second_id',$vv->id)
                        ->where('job_type_id',$val['job_type_id'])
                        ->whereNull('draw_time')//领取时间
                        ->count();
                    $job_type_list[$key]['wlq_count'] = $wlq_count;
                    //生产中
                    $scz_count = OrderChild::where('order_id',$vv->order_id)
                        ->where('order_second_id',$vv->id)
                        ->where('job_type_id',$val['job_type_id'])
                        ->where(function($q){
                            $q->whereNotNull('employee_user_id')->orWhere('is_epiboly','=',1);
                        })
                        ->whereNotNull('draw_time')
                        ->whereNull('submit_time')
                        ->count();
                    $job_type_list[$key]['scz_count'] = $scz_count;
                    //已完成
                    $ywc_count = OrderChild::where('order_id',$vv->order_id)
                        ->where('order_second_id',$vv->id)
                        ->where('job_type_id',$val['job_type_id'])
                        ->whereNotNull('submit_time')
                        ->count();
                    $job_type_list[$key]['ywc_count'] = $ywc_count;
                }
                $list[$k]['order_second'][$kk]['job_type_list'] = $job_type_list;
            }
            $order_child = OrderChild::where('order_id',$v->id)
                ->with(['job_type','employee'])
                ->select('order_second_id','order_id','job_type_id','employee_user_id','sort',DB::raw('count(*) as child_count'))
                ->groupBy('job_type_id')->get()->toArray();
            foreach($order_child as $kk=>$vv){
                //未领取
                $wlq_count = OrderChild::where('order_id',$vv['order_id'])
                    ->where('job_type_id',$vv['job_type_id'])
                    ->whereNull('draw_time')//领取时间
                    ->count();
                $order_child[$kk]['wlq_count'] = $wlq_count;
                //生产中
                $scz_count = OrderChild::where('order_id',$vv['order_id'])
                    ->where('job_type_id',$vv['job_type_id'])
                    ->where(function($q){
                        $q->whereNotNull('employee_user_id')->orWhere('is_epiboly','=',1);
                    })
                    ->whereNotNull('draw_time')
                    ->whereNull('submit_time')
                    ->count();
                $order_child[$kk]['scz_count'] = $scz_count;
                //已完成
                $ywc_count = OrderChild::where('order_id',$vv['order_id'])
                    ->where('job_type_id',$vv['job_type_id'])
                    ->whereNotNull('submit_time')
                    ->count();
                $order_child[$kk]['ywc_count'] = $ywc_count;
            }
            $list[$k]['order_child'] = $order_child;
        }

        return $list;
    }

    /**
     * 指派订单*
     * 仅指派未领取的
     */
    public function assignOrderChildRep($params){
        //$order_second_id = $params['order_second_id'];//子订单ID
        $order_id = $params['order_id'];
        $job_type_id = $params['job_type_id'];
        $num = $params['num'];
        $operator_user_id = $params['user_id'];
        $employee_user_id = $params['employee_user_id'];
        $where = [];
        $query = OrderChild::query();
        $query->where('order_id',$order_id);
        $query ->where('job_type_id',$job_type_id);
        $query->whereNull('employee_user_id');
        $query->whereNull('draw_time');
        //$query->whereNull('submit_time');
        $query->orderBy('product_num','asc');
        //$query->limit($num);
        $data = $query->get();
        foreach($data as $k=>$v){
            $v->operator_user_id=$operator_user_id;//操作人
            $v->employee_user_id=$employee_user_id;//指派员工ID
            $v->appoint_time=date("Y-m-d H:i:s",time());//订单领取/指派时间
            if($v->is_epiboly == 1){
                $v->is_epiboly = 2;
                $v->epiboly_time = null;
            }
            $v->is_appoint=1;
            $v->save();
            $orderRep = new OrderRep();
            $orderRep->setOrderProductionStatus($order_id,$v->order_second_id,1);//生产中
        }
//        $orderChild = OrderChild::where('order_id',$order_id)
//            ->where('order_second_id',$order_second_id)
//            ->where('job_type_id',$job_type_id)
//            ->whereNull('employee_user_id')
//            ->whereNull('draw_time')
//            ->inRandomOrder()
//            ->take($num)
//            ->update([
//                'operator_user_id'=>$operator_user_id,//操作人
//                'employee_user_id'=>$employee_user_id,//指派员工ID
//                'appoint_time'=>date("Y-m-d H:i:s",time()),//订单领取/指派时间
//                'is_appoint'=>1,
//            ]);
//        $orderRep = new OrderRep();
//        $orderRep->setOrderProductionStatus($order_id,$order_second_id,1);//生产中
        return $data;
    }

    /**外包订单**/
    public function epibolyOrderChildRep($params){
        $order_second_id = $params['order_second_id'];//子订单ID
        $orderChild = OrderChild::where('order_id',$params['order_id'])
            ->where('order_second_id',$order_second_id)
            ->where('job_type_id',$params['job_type_id'])
            ->whereNull('employee_user_id')
            ->whereNull('draw_time')
            ->inRandomOrder()
            ->take($params['num'])
            ->update([
                'epiboly_time'=>date("Y-m-d H:i:s",time()),//订单外包时间
                'is_epiboly'=>1,
                'status'=>2
            ]);
        $orderRep = new OrderRep();
        $orderRep->setOrderProductionStatus($params['order_id'],$order_second_id,1);//生产中
        return $orderChild;
    }

    /**
     * 根据订单id获取子订单列表
     * @param $params
     */
    public function getOrderChildListByOrderIdRep($params){
        $order_second_id = $params['order_second_id'];
        $list = OrderChild::Search($params)
            ->where('order_id',$params['order_id'])
            ->with(['job_type','employee'])
            ->orderBy('product_num','asc')
            ->get();
        return $list;
    }

    /**
     * 设置子订单状态为【完成】
     * @param $params
     */
    public function setOrderChildStatusRep($params){
        DB::beginTransaction();
        try{
            $child_order_ids = $params['child_order_ids'];//子订单ID
            foreach($child_order_ids as $k=>$child_order_id){
                $orderChild = OrderChild::where('id',$child_order_id)->first();
                $orderChild->operator_user_id = $params['user_id'];//操作人
                if($orderChild->is_epiboly == 1){
                    //已外包
                    $orderChild->status = 1;
                    $orderChild->submit_time = date("Y-m-d H:i:s",time());//提交时间
                    $orderChild->persion_id = $params['user_id'];//外包收货责任人
                }else{
                    if(empty($params['employee_user_id'])){
                        return ['code'=>1019,'msg'=>'尚未指派员工','data'=>[]];
                    }
                    $orderChild->employee_user_id = $params['employee_user_id'];//指派员工ID
                    $orderChild->appoint_time = date("Y-m-d H:i:s",time());//订单领取/指派时间
                    $orderChild->is_appoint = 1;
                    $orderChild->status = 1;
                    $orderChild->draw_time = date("Y-m-d H:i:s",time());//领取时间
                    $orderChild->submit_time = date("Y-m-d H:i:s",time());//提交时间
                }
                $orderChild->save();
                $orderRep = new OrderRep();
                $orderRep->setOrderProductionStatus($orderChild->order_id,$orderChild->order_second_id,1);//生产中
                if($orderChild->order_second_id){
                    $orderRep->selectOrderChildStatusBySecondId($orderChild->order_id,$orderChild->order_second_id);//加入半成品库
                }
                $orderRep->selectOrderChildStatusByOrderId($orderChild->order_id);//加入成品库
            }
            DB::commit();
            return ['code'=>0,'msg'=>'success','data'=>$orderChild];
        }catch(\Exception $exception){
            DB::rollBack();
            return ['code'=>2001,'msg'=>$exception->getMessage(),'data'=>[]];
        }

    }

    /**
     * 自动添加子订单
     * @param $product_id
     * @param $order_id
     */
    public function autoCreateOrderChild($order_id){
        $order_second = OrderSecond::where('order_id',$order_id)->get()->toArray();
        $order = Order::find($order_id);
        //p($order);
        $productRep = new ProductRep();
        $order_job_type_list = $productRep->getProductJobTypeListByProductId($order->product_id);
        $job_type_id_arr = [];
        foreach($order_second as $k=>$v){
            $job_type_list = $productRep->getProductJobTypeListByProductId($v['product_id']);
            //$num = $v['num'];
            if($v['is_kucun'] == 2){
                //添加生产子订单
                $nums = 0;
                $nums = $v['total_num'];
                for($i=0;$i<$nums;$i++){
                    foreach($job_type_list as $kk=>$vv){
                        $sort = $productRep->getProductJobTypeListSortRep($v['product_id'],$vv['id']);
                        $prict = $productRep->getPriceByJobTypeId($v['product_id'],$v['model_number_id'],$vv['id'],$v['specification_id']);
                        $orderChild = new OrderChild();
                        $orderChild->order_id = $order_id;
                        $orderChild->job_type_id = $vv['id'];
                        $orderChild->order_second_id = $v['id'];
                        $orderChild->sort = $sort;
                        $orderChild->price = $prict??0;
                        $orderChild->is_kucun = $v['is_kucun'];
                        $orderChild->product_num = $i+1;
                        $orderChild->save();
                    }
                }
                foreach($job_type_list as $kk=>$vv){
                    $job_type_id_arr[] = $vv['id'];
                }
            }else{
                //使用库存生成的子订单直接完成
                for($i=0;$i<$v['total_num'];$i++){
                    foreach($job_type_list as $kk=>$vv){
                        $sort = $productRep->getProductJobTypeListSortRep($v['product_id'],$vv['id']);
                        $prict = $productRep->getPriceByJobTypeId($v['product_id'],$v['model_number_id'],$vv['id'],$v['specification_id']);
                        $orderChild = new OrderChild();
                        $orderChild->order_id = $order_id;
                        $orderChild->job_type_id = $vv['id'];
                        $orderChild->order_second_id = $v['id'];
                        $orderChild->sort = $sort;
                        $orderChild->price = $prict??0;
                        $orderChild->is_kucun = $v['is_kucun'];
                        $orderChild->product_num = $i+1;
                        $orderChild->status = 1;
                        $orderChild->submit_time = date("Y-m-d H:i:s");
                        $orderChild->draw_time = date("Y-m-d H:i:s");
                        $orderChild->save();
                        //使用库存
                        $semi_ids = OrderKucunLog::where('order_second_id',$v['id'])
                            ->pluck('semi_ids')->toArray();
                        SemiFinishProduct::whereIn('id',$semi_ids)
                            ->update([
                                'production_order_child_id'=>$orderChild->id,
                                'is_del'=>1
                            ]);
                    }
                }
                foreach($job_type_list as $kk=>$vv){
                    $job_type_id_arr[] = $vv['id'];
                }
            }
        }

        for($i=0;$i<$order->num;$i++){
            foreach($order_job_type_list as $kk=>$vv){
                if(in_array($vv['id'],$job_type_id_arr)){
                    continue;
                }
                $sort = $productRep->getProductJobTypeListSortRep($order->product_id,$vv['id']);
                $prict = $productRep->getPriceByJobTypeId($order->product_id,$order->model_number_id,$vv['id'],$order->specification_id);
                $orderChild = new OrderChild();
                $orderChild->order_id = $order_id;
                $orderChild->job_type_id = $vv['id'];
                //$orderChild->order_second_id = $v['id'];
                $orderChild->sort = $sort;
                $orderChild->price = $prict??0;
                $orderChild->is_kucun = 2;
                $orderChild->product_num = $i+1;
                $orderChild->save();
            }
        }


    }

    /**
     * 修改子订单领单人
     * @return void
     */
    public function updateOrderChildEmployeeUserIdRep($employee_user_id,$order_child_id){
        $orderChild = OrderChild::where('id',$order_child_id)->first();
        if($orderChild){
            $orderChild->employee_user_id = $employee_user_id;
            $orderChild->appoint_time=date("Y-m-d H:i:s",time());//订单领取/指派时间
            $orderChild->is_appoint=1;
            $orderChild->save();
            return ['code'=>0,'msg'=>'success','data'=>$orderChild];
        }else{
            return ['code'=>2001,'msg'=>'子订单不存在或已删除','data'=>[]];
        }
    }



}
